package com.zs.zcerp.entrance;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwenze.poi.ExcelKit;
import com.wuwenze.poi.handler.ExcelReadHandler;
import com.wuwenze.poi.pojo.ExcelErrorField;
import com.zs.zcerp.entrance.entity.*;
import com.zs.zcerp.entrance.init.InitEntranceData;
import com.zs.zcerp.entrance.service.*;
import com.zs.zcerp.remark.service.CommonService;
import com.zs.zcerp.system.entity.User;
import com.zs.zcerp.system.service.IUserService;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时任务,用于定时更新门禁数据
 */
//@Configuration
//@EnableScheduling
public class EntranceScheduled {

    private final static Logger logger = LoggerFactory.getLogger(InitEntranceData.class);

    final static SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    final static SimpleDateFormat df1= new SimpleDateFormat("yyyy-MM-dd");

    final Base64.Encoder encoder = Base64.getEncoder();


    @Autowired
    private IDpDeptService dpDeptService;

    @Autowired
    private IEpMainService epMainService;

    @Autowired
    private IPostService postService;

    @Autowired
    private ISyorgService syorgService;

    @Autowired
    private IEntranceAccessService entranceAccessService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IEpPhotoService epPhotoService;

    @Autowired
    private IAttendanceService attendanceService;

    @Scheduled(cron = "0 0 12/22 * * ?")
    public void updateData() {

        logger.info(df.format(new Date()) + "开始定时更新数据...");

        // 定时更新公司信息
        updateSyorg();

        // 定时更新部门信息
        updateDept();

        // 定时更新职位信息
        updatePost();

        // 定时更新员工信息, 包括本系统的user信息与门禁用户信息
        updateUser();

        // 定时检查所有员工离职状态并更新门禁与本系统状态
        updateAllEmpStatus();

        // 定时更新员工排班
        List<Integer> orgIds = Arrays.asList(1100, 1201, 9000);
        for (Integer orgId : orgIds) {
            updateAttendance(orgId);
        }

        logger.info(df.format(new Date()) + "定时更新数据完毕");
    }



    void updateSyorg() {
        try {
            List<Syorg> syorgList = syorgService.listSyorgsLately();
            logger.info("待更新公司数量:" + syorgList.size());
            for (Syorg syorg : syorgList) {
                entranceAccessService.CreateOrUpdateSyorg(syorg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void updateDept() {
        // 记录父部门还未插入的部门,最后再更新
        List<DpDept> errDpDepts = new ArrayList<>();
        List<DpDept> dpDeptList = dpDeptService.listDpDeptsLately();
        logger.info("待更新部门数量:" + dpDeptList.size());
        for (DpDept dpDept : dpDeptList) {
            try {
                entranceAccessService.CreateOrUpdateDpDept(dpDept);
            } catch (Exception e) {
                errDpDepts.add(dpDept);
                e.printStackTrace();
            }
        }

        // 再次尝试更新错误的部门
        try {
            for (DpDept dpDept : errDpDepts) {
                logger.info("再次尝试更新部门" + JSON.toJSONString(dpDept));
                entranceAccessService.CreateOrUpdateDpDept(dpDept);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updatePost() {
        try {
            List<Post> postList = postService.listPostsLately();
            logger.info("待更新职位数量:" + postList.size());
            for (Post post : postList) {
                entranceAccessService.CreateOrUpdatePost(post);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void updateUser() {
        Page<EpMain> epMainPage = new Page<>(1,1000);
        List<EpMain> epMainList = epMainService.pageListEpMainsLately(epMainPage).getRecords();
        logger.info("待更新员工数量:" + epMainList.size());
        for (int i = 0; epMainList.size() > 0; i++) {
            for (EpMain epMain : epMainList) {
                try {
                    // 查询是否有重复工号
                    epMainService.findByEmpno(epMain.getEmpId());
                    // epMain添加照片信息
                    EpPhoto epPhoto = epPhotoService.findByEmpNo(epMain.getEmpCode());

                    if (epPhoto != null && epPhoto.getPhoto1() != null) {
                        epMain.setPhoto(encoder.encodeToString(epPhoto.getPhoto1()));
                    }
                    // 使empCode和empId 同为empId
                    epMain.setEmpCode(epMain.getEmpId());
                    // 设置员工状态
                    // 排除作废的员工
                    if ((epMain.getEmpLeaveDate() != null && epMain.getEmpLeaveDate().getTime() < System.currentTimeMillis()) || "0".equals(epMain.getEmpState())) {
                        epMain.setEmpState("0");
                        if (epMain.getEmpLeaveDate() != null) {
                            epMain.setEmpLeaveDate(epMain.getEmpLeaveDate());
                        } else {
                            epMain.setEmpLeaveDate(epMain.getHiredDate());
                        }
                    } else {
                        epMain.setEmpState("1");
                    }
                    // 更新门禁用户信息
                    logger.info(epMain.getEmpId() + epMain.getName());
                    entranceAccessService.CreateOrUpdateEmp(epMain);
                } catch (Exception e) {
                    logger.error(e.getMessage() + "更新门禁系统用户出错" + epMain.getName() + epMain.getEmpId());
                }

                // 更新本系统的user信息
                User user = new User();
                try {
                    // 查询用户是否已存在
                    User user0 = userService.findByName(epMain.getEmpId());

                    user.setUsername(epMain.getEmpId());
                    user.setCname(epMain.getName());
                    try {
                        user.setCname(commonService.findEmpnameByNo(epMain.getOrgId(), epMain.getEmpCode(), "T"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    user.setMobile(epMain.getMobile());

                    if ("M".equals(epMain.getGender())) {
                        user.setSex("0");
                    } else if ("F".equals(epMain.getGender())) {
                        user.setSex("1");
                    }

                    // 设置用户状态
                    user0.setStatus(epMain.getEmpState());
                    if (user0 != null) {
                        user.setRoleId(user0.getRoleId());
                        user.setUserId(user0.getUserId());
                        // 更新用户
                        userService.updateUser(user);
                        logger.info("更新本系统用户成功!" + user.getCname() + user.getUsername());
                    } else {
                        // 创建用户
                        user.setRoleId("84");
                        userService.createUser(user);
                        // 更新默认密码为身份证后六位
                        String certCode = epMain.getCertCode();
                        if (certCode != null && !certCode.isEmpty() && certCode.length() > 6) {
                            String subId = certCode.substring(certCode.length() - 6);
                            userService.updatePassword(user.getUsername(), subId);
                        }
                        logger.info("创建本系统用户成功!" + user.getCname() + user.getUsername());
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage() + "新增vitoryERP用户出错" + JSON.toJSONString(user));
                }
            }
            epMainPage.setCurrent(i);
            epMainList = epMainService.pageListEpMainsLately(epMainPage).getRecords();
        }
    }

    void updateAllEmpStatus() {
        List<EpMain> epMains = epMainService.listAllEmp();
        logger.info("开始更新所有离职员工状态...");
        for (EpMain e : epMains) {
            if ("1711016".equals(e.getEmpId())) {
                continue;
            }
            try {
                // 更新门禁系统
                EpMain epMain = new EpMain();
                // 使empCode和empId 同为empId
                epMain.setEmpCode(e.getEmpId());
                epMain.setEmpId(e.getEmpId());
                // 本系统信息
                User user0 = userService.findByName(e.getEmpId());
                if ((e.getEmpLeaveDate() != null && e.getEmpLeaveDate().getTime() < System.currentTimeMillis()) || "0".equals(e.getEmpState())) {
                    epMain.setEmpState("0");
                    if (e.getEmpLeaveDate() != null) {
                        epMain.setEmpLeaveDate(e.getEmpLeaveDate());
                    } else {
                        epMain.setEmpLeaveDate(e.getHiredDate());
                    }
                } else {
                    epMain.setEmpState("1");
                }
                // 更新门禁
                String s = entranceAccessService.UpdateEmp(epMain);
                logger.info("本次更新:" + JSON.toJSONString(epMain) + s);
                if (user0 != null) {
                    if (e.getEmpLeaveDate() != null && e.getEmpLeaveDate().getTime() < System.currentTimeMillis()) {
                        user0.setStatus("0");
                    } else {
                        user0.setStatus("1");
                    }
                    if (user0.getRoleId() == null) {
                        user0.setRoleId("84");
                    }
                    // 更新本系统
//                    userService.updateUser(user0);
                }
            } catch (Exception ex) {
                logger.info(ex.getMessage());
            }
        }
    }

    // 更新员工排班
    void updateAttendance(Integer orgId) {
        List<EpMain> epMains = epMainService.listEpMainsAttendance(orgId);
        int i = 0;
        for (EpMain e : epMains) {
            try {
                Date date = DateUtils.addDays(new Date(), 1);
                Attendance attendancd = attendanceService.attendanceByEmpNo(orgId,e.getEmpCode(), date);
                System.out.println("结果:==" + ++i + "===" + JSON.toJSONString(attendancd));
                attendancd.setEmpId(e.getEmpId());
                String nowTime = df1.format(date);
                attendancd.setDate(nowTime);
                attendancd.setB1sbtime(nowTime + " " + attendancd.getB1sbtime());
                if (Integer.parseInt(attendancd.getB1sbtime().substring(attendancd.getB1sbtime().lastIndexOf(" ") + 1).substring(0, 2)) > Integer.parseInt(attendancd.getB1xbtime().substring(attendancd.getB1xbtime().lastIndexOf(" ") + 1).substring(0, 2))) {
                    nowTime = df1.format(DateUtils.addDays(new Date(),  + 1));
                }
                attendancd.setB1xbtime(nowTime + " " + attendancd.getB1xbtime());
                if (attendancd.getB2sbtime() != null) {
                    attendancd.setB2sbtime(nowTime + " " + attendancd.getB2sbtime());
                    if (Integer.parseInt(attendancd.getB2sbtime().substring(attendancd.getB2sbtime().lastIndexOf(" ") + 1).substring(0, 2)) > Integer.parseInt(attendancd.getB2xbtime().substring(attendancd.getB2xbtime().lastIndexOf(" ") + 1).substring(0, 2))) {
                        nowTime = df1.format(DateUtils.addDays(new Date(),  + 1));
                    }
                    attendancd.setB2xbtime(nowTime + " " + attendancd.getB2xbtime());
                } else {
                    attendancd.setB2sbtime("");
                    attendancd.setB2xbtime("");
                }
                attendancd.setB3sbtime("");
                attendancd.setB3xbtime("");
                System.out.println("结果:" + JSON.toJSONString(attendancd));
                String s = entranceAccessService.UpdateAttendancePlan(attendancd);
                System.out.println(s);
            } catch (Exception exception) {
                logger.info("更新排班出错:" + exception.getMessage() + " , " + JSON.toJSONString(e));
            }
        }

        // 删除指定员工的排班
        File excelFile = new File("D://AttendanceDelete.xlsx");
        ExcelKit.$Import(Attendance.class).readXlsx(excelFile, new ExcelReadHandler<Attendance>() {
            @Override
            public void onSuccess(int i, int i1, Attendance attendance) {
                try {
                    attendance.setEmpId(attendance.getEmpCode().toUpperCase());
                    attendance.setDate(df1.format(DateUtils.addDays(new Date(), 1)));
                    System.out.println(i + "===" + i1 + "===" + JSON.toJSONString(attendance));
                    entranceAccessService.DeleteAttendancePlan(attendance);
                } catch (Exception e) {
                    logger.info("删除员工排班错误:====" + e.getMessage());
                }
            }

            @Override
            public void onError(int i, int i1, List<ExcelErrorField> list) {

            }
        });
    }

}
